# coding: utf-8

from leancloud import Object
from leancloud import Query
from leancloud import LeanCloudError
import json

class Games(Object):
    pass

class Favorite(Object):
    pass

class _User(Object):
    pass

def getList(userID):
    """
    :param userID: 用户名
    获取游戏列表
    """
    user = userID
    games = Query(Games).find()
    header = {'error':0,'errorInfo':''}
    gameList = []
    for game in games:
        gameName = game.get('gameName')
        describe = game.get('describe')
        view = game.get('views')
        item = {'gameName':gameName, 'describe':describe,'gameID':game.id, 'view':view}
        favoritesQuery = Query.and_(Query(Favorite).equal_to('user',user), Query(Favorite).equal_to('game',game))
        favorite = favoritesQuery.find()
        if favorite:
            item['favorite'] = True
        else:
            item['favorite'] = False
        gameList.append(item)
    header['gameList'] = gameList
    return json.dumps(header)

def addFavorite(gameID, userID):
    """
    :param userID: 用户名
    :param gameID: 游戏的ObjectID
    添加收藏
    """
    game = None
    user = None
    try:
        game = Query(Games).get(gameID)
        user = userID
    except LeanCloudError as e:
        header = {'error':1,'errorInfo':e.error}
        return json.dumps(heade)

    if game and user:
        favorite = Favorite()
        favorite.set('user', user)
        favorite.set('game', game)
        try:
            favorite.save()
        except LeanCloudError as e:
            header = {'error':2,'errorInfo':e.error}
        header = {'error':0,'errorInfo':''}
        return json.dumps(header)
    else:
        header = {'error':1,'errorInfo':'failed'}
        return json.dumps(header)


def rmFavorite(gameID, userID):
    """
    :param userID: 用户名
    :param gameID: 游戏的ObjectID
    移除收藏
    """
    user = None
    game = None
    try:
        user = userID
        game = Query(Games).get(gameID)
    except LeanCloudError as e:
        header = {'error':1,'errorInfo':e.error}
        return json.dumps(header)
    if user and game:
        favorites = Query.and_(Query(Favorite).equal_to('user',user), Query(Favorite).equal_to('game',game)).find()
        for favorite in favorites:
            favorite.destroy()
        header = {'error':0,'errorInfo':''}
        return json.dumps(header)

def click(gameID):
    """
    :param gameID: 游戏的ObjectID
    点击时间叠加
    """
    try:
        game = Query(Games).get(gameID)
        if game:
            game.increment('views').save()
            header = {'error':0,'errorInfo':''}
            return json.dumps(header)
        else:
            header = {'error':2,'errorInfo':'game obj is empty!'}
            return json.dumps(header)
    except LeanCloudError as e:
        header = {'error':1,'errorInfo':e.error}
        return json.dumps(header)

if __name__ == '__main__':
    # 只在本地开发环境执行的代码
    print(getList(''))
